package android.tusnotas.activities;


import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.tusnotas.activities.extras.ShowCourseActivityExtras;
import android.tusnotas.activities.extras.ShowGroupActivityExtras;
import android.tusnotas.beans.Course;
import android.tusnotas.beans.Group;
import android.tusnotas.beans.Person;
import android.tusnotas.core.GroupAnalyser;
import android.tusnotas.model.TusNotasModel;
import android.tusnotas.services.WebCheckerManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ShowGroup extends CommonActivity {

	private ProgressDialog pd;
	private Thread thread = null;

	private Course course = null;
	private Group group = null;
	private TusNotasModel tusNotasModel = null;
	private String errorMessage = null;
	//private Menu menu = null;
	private KillReceiver mKillReceiver;
	private WebCheckerManager webCheckerManager = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mKillReceiver = new KillReceiver();
		IntentFilter intentFilter = new IntentFilter("kill");
		registerReceiver(mKillReceiver,	intentFilter);

		webCheckerManager = new WebCheckerManager(this);

		setContentView(R.layout.show_group);
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		tusNotasModel = TusNotasModel.getTusNotasModel(getApplicationContext());
		webCheckerManager = new WebCheckerManager(this);

		initilizeThread();
		this.thread.start();
	}

    @Override
    protected void onDestroy() {
        unregisterReceiver(mKillReceiver);
        super.onDestroy();
    }

    private void initilizeThread(){
		pd = ProgressDialog.show(this, 
				getResources().getString(R.string.process_dialog_title_loading),
				getResources().getString(R.string.process_dialog_message_loading),
				Boolean.TRUE, Boolean.FALSE);
		this.thread = new Thread( new Runnable() {
			@Override
			public void run() {
				dataLoader(getIntent());
				pd.dismiss();
				h.sendEmptyMessage(0);
			}
		});
	}

	final Handler h = new Handler(){
		public void handleMessage(Message msg) {
			drawList();
		}           
	};

	public void drawList(){

		// if there's no group info, notify
		if (this.group==null){

			TextView groupName = (TextView) findViewById(R.id.group_name);
			groupName.setText(getString(R.string.message_no_group));
			
			// hide options
			TableRow row1 = (TableRow) findViewById(R.id.generalOptionsRow1);
			TableRow row2 = (TableRow) findViewById(R.id.generalOptionsRow2);
			((ViewGroup) row1.getParent()).removeView(row1);
			((ViewGroup) row2.getParent()).removeView(row2);

		} else {

			TextView groupName = (TextView) findViewById(R.id.group_name);
			groupName.setText(group.getName());

			TableLayout tableLayout = (TableLayout) findViewById(R.id.group_members_table);
			tableLayout.removeAllViews();

			TableRow tableRow = null;
			TextView textViewName = null;

			ViewGroup.LayoutParams layoutParams = ((TextView) findViewById(R.id.group_downloads)).getLayoutParams();

			for(Person person : this.group.getPersons()){//tusNotasModel.selectPersonsByGroup(course.getGroup().getId())) {

				tableRow = new TableRow(getApplicationContext());

				tableRow.setBackgroundDrawable(getResources().getDrawable(R.drawable.course_table_element));

				textViewName = new TextView(getApplicationContext());

				textViewName.setLayoutParams(layoutParams);

				textViewName.setGravity(Gravity.CENTER_VERTICAL);

				textViewName.setText(person.getName());
				textViewName.setTextColor(Color.BLACK);

				tableRow.addView(textViewName);

				tableLayout.addView(tableRow);
			}
		}
	}

	private Integer dataLoader(Intent intent){
		Integer courseId = intent.getIntExtra(ShowCourseActivityExtras.COURSE_ID, -1);
		intent.removeExtra(ShowCourseActivityExtras.COURSE_ID);
		if (courseId == -1) {
			return courseId;
		}
		this.course = tusNotasModel.selectCoursesById(courseId);
		GroupAnalyser groupAnalyser = new GroupAnalyser();
		try {
			this.group = groupAnalyser.doGetGroup(course.getIdAula());
		} catch (Exception e) {
			this.errorMessage = getString(R.string.message_error_group);
		}
		return 1;
	}

	private final class KillReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}
	}

	public void gotoFiles(View view){
		if (!group.getFiles().isEmpty()) {
			try {
				Intent showFilesIntent =  new Intent(getApplicationContext(), ShowFiles.class);
				showFilesIntent.putParcelableArrayListExtra(ShowGroupActivityExtras.GROUP_FILES_KEY, (ArrayList<? extends Parcelable>) group.getFiles());
				startActivity(showFilesIntent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Toast t = Toast.makeText(getApplicationContext(),R.string.toast_no_group_files, Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();
		}
	}

	public void gotoMessages(View view){
		try {
			// if there is at least one message
			if (!group.getMessages().isEmpty()){
				Intent showMessagesIntent =  new Intent(getApplicationContext(), ShowMessages.class);
				showMessagesIntent.putParcelableArrayListExtra(ShowGroupActivityExtras.GROUP_MESSAGES_KEY, (ArrayList<? extends Parcelable>) group.getMessages());
				showMessagesIntent.putExtra(ShowGroupActivityExtras.GROUP_ID, this.group.getId().toString());
				showMessagesIntent.putExtra(ShowCourseActivityExtras.COURSE_ID, this.course.getIdAula());
				startActivity(showMessagesIntent);
			} else {
				Intent showMessagesIntent =  new Intent(getApplicationContext(), ShowMessages.class);
				showMessagesIntent.putExtra(ShowGroupActivityExtras.GROUP_ID, this.group.getId().toString());
		    	showMessagesIntent.putExtra(ShowCourseActivityExtras.COURSE_ID, this.course.getIdAula().toString());
				startActivity(showMessagesIntent);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
